package ru.hh.school.commands;

import ru.hh.school.Room;
import ru.hh.school.User;
import ru.hh.school.UserManager;
import ru.hh.school.logging.Logger;

import static ru.hh.school.MessagesManager.message;

public class QuitCommand extends AbstractCommand {
    private final UserManager manager;

    public QuitCommand(Logger logger, UserManager manager) {
        super(logger);
        this.manager = manager;
    }

    public String getCommand() {
        return "/quit";
    }

    public String getDescription() {
        return message("command.quit.description");
    }

    void logCommand(User user, String data) {
        synchronized (user) {
            if (user.isAlive()) {
                super.logCommand(user,data);
            }
        }
    }

    @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
    public void process(User user, String lastWord) {
        synchronized (user) {
            if (user.isAlive()) {
                Room room = user.getRoom();
                String nick = user.getNick();
                user.close();
                if (nick != null) {
                    if (lastWord.equals("")) {
                        room.send(message("command.quit.notify.room.user.quit.default.message", nick));
                    } else {
                        room.send(message("command.quit.notify.room.user.quit", nick, lastWord));
                    }
                    manager.giveBackNick(nick);
                }
            }
        }
    }
}